<template>
	<van-uploader :after-read="afterRead" :before-read="beforeRead" v-show="visible">
		<div class='van-cell van-field'>
			<div v-if="!noLabel" class="van-cell__title van-field__label">{{componentModel.label}}</div>
			<van-image width="60" height="40" :src="imageUrl" />
		</div>
	</van-uploader>
</template>

<script>
	import constants from '@/utils/constants.js';
	import utils from '@/utils/utils.js';
	export default {
		name: "ImageComponent",
		props: ["componentModel", "actionScope", "rowData"],
		data() {
			return {
				imageUrl: "",
				noLabel: false,
				filename:null,
				visible:true
			}
		},
		inject: ['children'],
		mounted() {
			if (this.rowData != undefined) {
				this.imageUrl = constants.ROOT_URL + "image/getImageByField?model=" + this.componentModel.model + "&id=" +
					this.rowData["id"] + "&dataField=" + this.componentModel.dataField + "&X-Token=" + window.localStorage
					.getItem("token");
				this.noLabel = true;
				this.filename=null;
			}
			this.children.push(this);
		},beforeUnmount() {
			utils.removeArrayElement(this.children,this);
		},
		methods: {
			setProp(prop) {
				var currentId = prop["currentId"];
				if (currentId == undefined || currentId == null) {
					this.imageUrl = "";
				} else {
					this.imageUrl = constants.ROOT_URL + "image/getImageByField?model=" + this.componentModel.model +
						"&id=" + currentId + "&dataField=" + this.componentModel.dataField + "&X-Token=" + window
						.localStorage.getItem("token");
				}
				var visible=prop["visible"];
				if(visible!=undefined){
					this.visible=visible;
				}
			},afterRead(file) {
				let formdata = new FormData();
				formdata.append('file', file.file);
				let config = {
					headers: {
						'Content-Type': 'multipart/form-data'
					}
				};
				var url = constants.ROOT_URL + "image/upload";
				this.axios.post(url, formdata, config).then((response) => {
					this.filename=response.data.filename;
					this.imageUrl=constants.ROOT_URL + "image/getImageByFilename?filename="+response.data.filename+"&X-Token="+window.localStorage.getItem("token");
				});
			},beforeRead(){
				if (this.rowData != undefined) {
					return false;
				}
				return true;
			},getValue(){
				if(this.filename==null){
					return undefined;
				}
				return this.filename;
			},
		},
	}
</script>

<style>
</style>
